# -*- coding: utf8 -*-

from sqlalchemy import create_engine, __version__
from sqlalchemy.orm import sessionmaker, scoped_session

print("sqlalchemy: %r" % (__version__,) )

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool

@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        # optional - dispose the whole pool
        # instead of invalidating one at a time
        # connection_proxy._pool.dispose()

        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close()

class DataBase(object):
    
    db = None
    
    engine = None

    def init( self, db = {} ):
        self.db = {
            "dialect" : "sqlite",
            "connection" : "",
            "database" : ":memory:",
            "options" : ""
        }
        
        self.db.update(db)
        
        print("connect uri = %(dialect)s://%(connection)s/%(database)s%(options)s" % self.db)

        self.engine = None
        self.Session = None
        pass

    def getEngine(self):
        if not self.engine:
            self.engine = create_engine("%(dialect)s://%(connection)s/%(database)s%(options)s" % self.db,
                pool_size=16, pool_recycle=30,
                convert_unicode=True,
                # echo=True,
                # echo_pool=True,
                strategy='threadlocal'
            )
        return self.engine

    def getSession(self):
        if not self.Session:
            self.Session = scoped_session( sessionmaker(bind=self.getEngine()) )
            # self.Session = sessionmaker(bind=self.getEngine())
        return self.Session()


database = DataBase()
